home *** CD-ROM | disk | FTP | other *** search
- Path: wintermute.ecs.fullerton.edu!titan!grosin
- From: grosin@titan (Gil Rosin)
- Newsgroups: comp.lang.c++
- Subject: How do I put DIFFERENT classes in the same linked list?
- Date: 8 Apr 1996 05:44:08 GMT
- Organization: California State University at Fullerton
- Message-ID: <4ka938$bj6@wintermute.ecs.fullerton.edu>
- NNTP-Posting-Host: titan.ecs.fullerton.edu
- X-Newsreader: TIN [version 1.2 PL2]
-
- I'm trying to write a program where I need to maintain a linked list of
- various items. Each item is a class, but each item is different from another
- item. Let me give an example to clarify:
-
- A library catalog for example, there is a BOOK class and a MAGAZINE class,
- then there is an ITEM class from which BOOK and MAGAZINE are derivided (Tell
- me if there is a better way to do this!!). ITEM has a ITEM *next pointer.
-
- Now, I want to be able to basically construct a linked list of BOOK and
- MAGAZINE classes with out really knowing which one is which.
-
- Here is the source code I have worked up so far:
-
- #include <iostream.h>
-
- class A
- {
- public:
- A *next;
- A *prev;
- void Print();
- };
-
- class Demo
- {
- public:
- void Insert(A *Temp);
- void Insert2(A *Temp);
- void Test(void);
- A *First;
- };
-
- class B : public A
- {
- void Print();
- };
-
- class C : public A
- {
- void Print();
- };
-
- main()
- {
- Demo *T = new Demo;
- A *Test = new B;
- T->Insert(Test);
- Test = new C;
- T->Insert2(Test);
- T->Test();
- return 0;
- }
-
- void B::Print()
- {
- cout << "I am in class B" << '\n';
- }
-
- void C::Print()
- {
- cout << "I am in class C" << '\n';
- }
-
- void Demo::Insert(A *Temp)
- {
- First = Temp;
- }
-
- void Demo::Insert2(A *Temp)
- {
- First->next = Temp;
- }
-
- void Demo::Test(void)
- {
- First->Print();
- First->next->Print();
- }
-
- void A::Print()
- {
- cout << "I am in class A" << '\n';
- }
-
- Now, as you can see, I want to have a linked list that contains EITHER
- B or C Items, but in the void Demo::Test() function, I want to be able to
- just call them blindly with out knowing which is which. When I compile this
- I get NO errors, but when I run it the two lines that print out are the
- class A print function. It should print out the class B and then the class C.
-
- How can I do this? I am not worrying about constructors/destructors etc
- right now, just worrying about how to get it to work.
-
- Thanks. Please reply via email to grosin@titan.fullerton.edu.
-
-
-